package com.pdd.controller;

import io.swagger.annotations.Api;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @创建时间: 2018/8/20 - 14:42
 * @编写人员: 丷教皇
 * @文件描述: 用于做文件上传的控制器
 */
@Controller
@Api(description = "文件上传接口")
public class UploadController {

    @CrossOrigin(origins = {"*"})
    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> upload(MultipartFile multipartFile, HttpServletRequest request){
        String fileName = multipartFile.getOriginalFilename();
        long size = multipartFile.getSize();

        System.out.println("文件名" + fileName);
        System.out.println("大小" + size);

        //截取文件后缀名
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);

        //随机生成新文件名
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddmmssms");
        String time = sdf.format(new Date());

        //随机生成新文件名，4位随机数
        Random random = new Random();
        int ranNum = random.nextInt(9000) + 1000;

        //拼接，获取目标文件名(要储存在服务器中的文件名)
        String  targetName = time + ranNum + "." +  suffix;

        //上传的目标文件夹
        String uploadDir = request.getServletContext().getRealPath("/upload");
        System.out.println(uploadDir);

        //如果目标文件夹不存在
        File dir = new File(uploadDir);
        if(!dir.exists()){
            dir.mkdir();
        }

        //将上传的文件写入到目标位置
        File uploadFile = new File(uploadDir,targetName);
        try {
            multipartFile.transferTo(uploadFile);
        } catch (IOException e) {
            e.printStackTrace();
        }

        Map<String,Object> map = new HashMap<>(0);
        map.put("file","/upload" + targetName);
        map.put("size",size);

        return map;
    }

}
